<template>
  <div class="app-container page-container right-side-dialog" :style="{height: height + 'px'}">
    <!-- 搜索条件 -->
    <div class="header-search single_line">
      <el-form ref="search_form" :model="search" :inline="true" label-width="0">
        <div class="form-area">
          <div class="search_view">
            <el-form-item>
              <el-input v-model="search.docker_name" placeholder="请选择服务器" readonly @focus="serverVisible = true" />
            </el-form-item>
            <!--                        <el-button type="success" size="mini" round @click="connectServer()">连接</el-button>-->
            <!--            <el-button type="danger" size="mini" round @click="disconnectServer()">断开</el-button>-->
            <el-form-item>
              <el-select v-model="path" placeholder="选择路径(先选择服务器)">
                <el-option v-for="(item,index) in paths" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <div class="btn-area">
              <!-- <el-button type="primary" size="mini" round @click="getPaginateData()">获取列表</el-button> -->
              <el-button size="mini" round @click="resetData()">重置</el-button>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <!-- 搜索条件 -->

    <!-- 表格 -->
    <div class="content_view" style="height: 95%">
      <!-- 操作按鈕 -->
      <div v-show="!logWindow" style="overflow-y:scroll;height: 100%">
        <el-table
          :data="data"
          style="width: 100%"
          row-key="id"
          border
          lazy
          :load="load"
          height="100%"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @cell-click="rowClick"
        >
          <el-table-column prop="file_type" label="文件列表">
            <template slot-scope="scope">
              <icon-svg v-if="scope.row.file_type ==0" icon-class="weizhiwenjian" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==1" icon-class="txt" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==2" icon-class="wenjian" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==3" icon-class="pdf" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==4" icon-class="xlsx" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==5" icon-class="ppt" style="font-size: 1rem;" />
              <icon-svg v-if="scope.row.file_type ==6" icon-class="word" style="font-size: 1rem;" />
              {{ scope.row.file_name }}
              <el-button
                v-if="scope.row.file_type ==1"
                type="success"
                size="mini"
                icon="el-icon-d-arrow-right"
                style="padding: 0 6px;margin-left: 5px;"
                round
                @click="examine(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--    查看日志窗口 开始-->
      <div v-show="logWindow" style="height: 100%" class="logClass">
        <!--        日志搜索-->
        <el-form :inline="true" :model="log" class="demo-form-inline">
          <el-form-item label="">
            自动刷新
            <el-switch v-model="log.renovate" />
          </el-form-item>
          <el-form-item v-if="log.renovate" style="width: 100px;">
            <el-select v-model="log.time" placeholder="">
              <el-option label="3秒" value="3" />
              <el-option label="10秒" value="10" />
              <el-option label="30秒" value="30" />
              <el-option label="60秒" value="60" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="!log.renovate" label="起始行">
            <el-input
              v-model="log.startLineCount"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              autocomplete="off"
              style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="读取行数">
            <el-input
              v-model="log.lineCount"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="4"
              autocomplete="off"
              style="width: 110px;"
            />
          </el-form-item>
          <el-form-item label="编码格式">
            <el-select v-model="log.charset" placeholder="" filterable style="width: 150px;">
              <el-option
                v-for="(item,index) in charset"
                :key="index"
                :label="item"
                :value="item"
                style="font-size:13px"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-show="!log.renovate" type="primary" size="mini" round @click="queryLog()">获取</el-button>
          </el-form-item>
          <el-form-item>
            <el-badge :value="selectLog.length" class="item">
              <el-button type="success" size="mini" round @click="selectContent">对比</el-button>
            </el-badge>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="mini" icon="el-icon-back" circle @click="callBack" />
          </el-form-item>
        </el-form>
        <div style="height: 95%;display: inline-flex;width: 100%">
          <!--                  日志-->
          <div :style="{height:100+'%',width: width+'%'}">
            <div ref="logContentDiv" :style="{height: logContentHeight+'px'}" @contextmenu.prevent="rightClick">
              <el-table
                ref="logTable"
                :data="logContent"
                stripe
                style="width: 100%;"
                height="100%"
                highlight-current-row
              >
                <el-table-column prop="line" width="50" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div style="user-select: none">{{ scope.row.line }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="data" :label="fileName" show-overflow-tooltip />
              </el-table>
              <div v-show="menuVisible">
                <ul id="menu" class="menu">
                  <el-button type="danger" round @click="selectContent">加入对比</el-button>
                </ul>
              </div>
            </div>
            <!--            日志查找-->
            <hr style="cursor: move;margin: 0;height: 5px;" @mousedown="moveDiv">
            <div ref="logSearchDiv" :style="{height: logSearchHeight+'px'}">
              <el-table
                ref="searchLogTable"
                :data="searchLogContent"
                height="100%"
                highlight-current-row
                @row-click="searchLogTableRowClick"
              >
                <el-table-column>
                  <template slot="header" slot-scope="scope">
                    <el-input v-model="input" size="mini" placeholder="输入关键字搜索">
                      <el-button slot="append" icon="el-icon-search" @click="searchLog" />
                    </el-input>
                  </template>
                  <template slot-scope="scope">{{ scope.row.data }}</template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!--          日志对比-->
          <div v-show="selectLogStatus" type="textarea" style="height: 98%;width: 50%;overflow-y:scroll;">
            <el-steps direction="vertical" :active="selectLog.length" process-status="finish" :space="100">
              <el-button type="danger" plain @click="clearAll()">清空所有</el-button>
              <el-step v-for="(item,index) in selectLog" :key="index">
                <template slot="description">
                  <code-diff v-if="index==0" :new-string="selectLog[index]" :context="10" />
                  <code-diff
                    v-if="index > 0"
                    :old-string="selectLog[index-1]"
                    :new-string="selectLog[index]"
                    :context="10"
                    render-nothing-when-empty
                  />
                  <div v-if="index > 0 && index === selectLog.length -1" class="buttomLine">
                    <el-divider content-position="center">END</el-divider>
                  </div>
                  <el-link class="clearThis" icon="el-icon-circle-close" style="color: red" @click="clearThis(index)" />
                </template>
              </el-step>
            </el-steps>
          </div>
        </div>
      </div>
      <!--    查看日志窗口 结束-->

    </div>
    <!-- 选择服务器 -->
    <el-dialog
      title="选择服务器"
      :visible.sync="serverVisible"
      :close-on-click-modal="false"
      width="720px"
      class="server_view"
    >
      <el-scrollbar wrap-class="vertical_scrollbar" :style="{height: height + 'px'}">
        <SelectServer @selectServer="selectServer" />
      </el-scrollbar>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import SelectServer from '@/components/SelectServer'
import { basePostRequest, connect, disconnect } from '@/api/public'
import CodeDiff from 'vue-code-diff'

export default {
  components: { SelectServer, CodeDiff },
  data() {
    return {
      height: window.innerHeight - 100,
      auth: {},
      search: {},
      lastLogContent: '',
      serverVisible: false,
      paths: [],
      data: [],
      logWindow: false,
      log: {
        renovate: true,
        time: '3',
        startLineCount: 1,
        lineCount: 500,
        charset: 'UTF-8'
      },
      charset: ['ASCII', 'GBK', 'GB2312', 'GB18030', 'UTF-8', 'ISO-8859-1', 'UNICODE'],
      logContent: [],
      rowPath: '',
      fileName: '',
      menuVisible: false,
      selectLogStatus: false,
      selectLog: [],
      path: '',
      width: 100,
      input: '',
      searchLogContent: [],
      logContentHeight: (window.innerHeight - 100) * 0.95 * 0.95 * 0.65,
      logSearchHeight: (window.innerHeight - 100) * 0.95 * 0.95 * 0.34,
      myVar: ''
    }
  },
  computed: {
    ...mapState({
      permission: state => state.permission.permission
    })
  },
  watch: {
    logWindow: function() {
      if (this.logWindow) {
        Object.assign(this.$data.log, this.$options.data().log)
        this.$data.selectLog = []
        this.$data.selectLogStatus = false
        if (this.log.renovate && !this.myVar) {
          this.myVar = setInterval(() => {
            this.queryLog()
            this.$refs.logTable.bodyWrapper.scrollTop = this.$refs.logTable.bodyWrapper.scrollHeight
          }, this.log.time * 1000)
        }
      } else {
        clearInterval(this.myVar)
        this.myVar = ''
      }
    },
    path: function() {
      if (this.path != this.$store.state.log.data.path) {
        this.logWindow = false
      }
      basePostRequest('api/docker/logger/file/list', {
        server_id: this.search.server_id,
        base_path: this.path,
        file_path: ''
      }).then(resp => {
        if (resp) {
          this.data = JSON.parse(resp.data);
        }
      })
    },
    selectLog: function() {
      if (this.selectLog.length === 0) {
        this.selectLogStatus = false
        this.width = 100
      } else {
        this.width = 50
      }
    },
    log: {
      handler: function() {
        if (this.log.renovate) {
          if (this.logWindow && !this.myVar) {
            this.myVar = setInterval(() => {
              this.queryLog()
              this.$refs.logTable.bodyWrapper.scrollTop = this.$refs.logTable.bodyWrapper.scrollHeight
            }, this.log.time * 1000)
          }
          this.log.startLineCount = 1
        } else {
          clearInterval(this.myVar)
          this.myVar = ''
        }
      },
      deep: true
    }
  },
  mounted() {
    Object.assign(this.$data, this.$store.state.log.data)
  },
  created() {
    this.permissionAuth()
  },
  beforeDestroy() {
    clearInterval(this.myVar)
    this.myVar = ''
    this.$store.commit('commitLogData', this.$data)
  },
  methods: {
    callBack() {
      this.logWindow = false
      this.searchLogContent = []
      clearInterval(this.myVar)
      this.myVar = ''
    },
    moveDiv(e) {
      const initY = e.clientY
      const logContentHeight = this.logContentHeight
      const logSearchHeight = this.logSearchHeight
      document.onmousemove = e => {
        this.logContentHeight = logContentHeight + ((e.clientY - initY))
        this.logSearchHeight = logSearchHeight - ((e.clientY - initY))
      }
      document.onmouseup = e => {
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    searchLogTableRowClick(row, column, event) {
      this.$refs.searchLogTable.setCurrentRow(row)
      this.$refs.logTable.setCurrentRow(row)
      const scrollHeight = this.$refs.logTable.bodyWrapper.scrollHeight
      this.$refs.logTable.bodyWrapper.scrollTop = (scrollHeight * this.logContent.indexOf(row) / this.logContent.length)
    },
    searchLog() {
      if (!this.input) {
        this.$notify({
          title: '提示',
          message: '请输入关键字',
          type: 'warning'
        })
        return
      }
      this.searchLogContent = []
      const searchLog = this.logContent
      const input = this.input
      for (const searchLogElement of searchLog) {
        if (searchLogElement.data.search(input) >= 0) {
          this.searchLogContent.push(searchLogElement)
        }
      }
    },
    rowClick(row, column, cell, event) {
      if (row.hasChildren) {
        cell.getElementsByTagName('div')[1].click()
      }
    },
    // 清空所有所选日志
    clearAll() {
      this.$confirm('确认清空？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectLog = []
      }).catch(() => {
      })
    },
    // 清空单条日志
    clearThis(index) {
      this.selectLog.splice(index, 1)
    },
    selectContent() {
      const txt = window.getSelection().toString()
      if (txt.trim() == '') {
        this.$notify({
          title: '提示',
          message: '请选择比对内容',
          type: 'warning'
        })
        return
      }
      this.selectLogStatus = true
      this.selectLog.push(txt.replace(/\n[0-9]*\s*/g, '\n'))
    },
    // 鼠标右击触发事件
    rightClick(MouseEvent) {
      // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
      this.menuVisible = false
      // 显示模态窗口，跳出自定义菜单栏
      this.menuVisible = true
      var menu = document.querySelector('#menu')
      menu.style.left = MouseEvent.clientX - 80 + 'px'
      // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
      document.addEventListener('click', this.foo)
      menu.style.top = MouseEvent.clientY - 50 + 'px'
    },
    // 取消鼠标监听事件 菜单栏
    foo() {
      this.menuVisible = false
      // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
      document.removeEventListener('click', this.foo)
    },
    // 查询日志
    queryLog() {
      basePostRequest('/api/docker/logger/read/last/line', {
        server_id: this.search.server_id,
        base_path: this.path,
        file_path: this.rowPath,
        charset: this.log.charset,
        read_line: this.log.lineCount,
        start_line: this.log.startLineCount
      }).then(resp => {
        if (resp) {
          this.logContent = resp.data
        }
      })
    },
    // 查看
    examine(row) {
      this.logWindow = true
      this.rowPath = row.path
      this.fileName = row.file_name
      this.queryLog()
    },
    load(tree, treeNode, resolve) {
      basePostRequest('api/docker/logger/file/list', {
        server_id: this.search.server_id,
        base_path: this.path,
        file_path: tree.path
      }).then(resp => {
        if (resp) {
          resolve(JSON.parse(resp.data))
        }
      })
    },
    // 获取按钮权限
    permissionAuth() {
      this.auth.start = this.permission.indexOf('/api/docker/container/start')
      this.auth.stop = this.permission.indexOf('/api/docker/container/stop')
      this.auth.restart = this.permission.indexOf('/api/docker/container/restart')
    },
    // 重置搜索选项
    resetData() {
      // this.disconnectServer()
      Object.assign(this.$data, this.$options.data())
    },
    // 选择服务器
    selectServer(data) {
      this.serverVisible = false
      this.search.server_id = data.server_id
      this.search.docker_name = data.docker_name
      // this.connectServer()
      basePostRequest('/api/docker/logger/base/path', { server_id: this.search.server_id }).then(resp => {
        if (resp) {
          this.paths = JSON.parse(resp.data);
        }
      })
    },
    // 连接服务
    // connectServer() {
    //   if (!this.search.server_id) {
    //     this.$notify({
    //       title: '提示',
    //       message: '请选择服务器',
    //       type: 'warning'
    //     })
    //     return
    //   }
    //   connect(this.search.server_id).then(response => {
    //     this.$notify({
    //       title: '成功',
    //       message: '连接成功',
    //       type: 'success'
    //     })
    //   })
    // },
    // 断开服务
    disconnectServer() {
      if (!this.search.server_id) {
        this.$notify({
          title: '提示',
          message: '请选择服务器',
          type: 'warning'
        })
        return
      }
      disconnect(this.search.server_id).then(response => {
        this.$notify({
          title: '提示',
          message: '连接已断开',
          type: 'warning'
        })
        this.paths = []
      })
    },
    // 获取列表
    getPaginateData() {
      if (!this.path) {
        this.$notify({
          message: '请选择路径',
          type: 'warning'
        })
        return
      }
      basePostRequest('api/docker/logger/file/list', {
        server_id: this.search.server_id,
        base_path: this.path,
        file_path: ''
      }).then(resp => {
        if (resp) {
          this.data = resp.data;
        }
      })
    }
  }
}
</script>
<style lang="scss">
.d2h-info, .d2h-code-linenumber {
  display: none;
}

.d2h-code-line {
  padding: 0 0em;
}

.logClass .el-table--medium th, .logClass .el-table--medium td {
  padding: 0 0;
}

.logClass .el-table .cell {
  line-height: 23px;
}

.el-table--striped .el-table__body tr.el-table__row--striped.current-row td, .el-table__body tr.current-row > td {
  color: #fff;
  background-color: lightskyblue !important;
}

.font_red {
  color: #FF5722;
}

.menu__item {
  display: block;
  line-height: 25px;
  text-align: center;
}

.menu {
  position: absolute;
  z-index: 99999;
  padding-inline-start: 0px;
}

.el-dialog__body {
  height: 90%;
}

.clearThis {
  font-size: 20px;
  position: absolute;
  right: 0px;
  top: 0px
}

.el-step__description {
  padding-right: 0;
}

.el-table--medium th, .el-table--medium td {
  padding: 3px 0;
}

.logClass .el-table .cell {
  line-height: 20px;
}

.el-badge__content.is-fixed {
  top: 6px;
  right: 15px;
}

.el-step__main {
  overflow: auto;
}

.buttomLine {
  margin-bottom: 80px;
  margin-top: -10px;
}

.el-divider__text {
  color: #c1c1c1;
  font-size: 10px;
}

.el-button--danger.is-plain {
  height: 10px;
  font-size: 13px;
}

.el-button--danger.is-plain span {
  position: relative;
  top: -6px;
}

.el-step__icon.is-text {
  width: 20px;
  height: 20px;
  font-size: 12px;
  left: 2px;
  top: -1px;
}
</style>
